<?php

namespace app\v1\model;

use think\Model;
use think\Db;

/**
 * Class Device
 * @package app\v1\model
 * 模块说明：这个模块主要用来处理监控模块的数据处理，监控的接口数据处理都在这个类里头处理
 */

class Device extends Base
{
    //获取设备列表的配置
    public function getDeviceConfig(){
        $redis=getRedis();
        $userInfo=getUserInfo();
        if(empty($redis->get('deviceList'.$userInfo['parentId']))) {
            $ezDeviceList = $this->getEzDeviceList();
            $nvrDeviceList = $this->getNvrDeviceList();
            $list = array_merge($ezDeviceList, $nvrDeviceList);
           // $data = array('ezDeviceList' => $ezDeviceList, 'nvrDeviceList' => $nvrDeviceList);
            $redis->set('deviceList'.$userInfo['parentId'],$list,120);
      }else{
            $list=$redis->get('deviceList'.$userInfo['parentId']);
        }
        //$redis->set('deviceList'.$userInfo['parentId'],$list,5);
        renderData(0,'ok',$list);
    }

    //获取ez的设备列表
    public function getEzDeviceList(){
        $userInfo=getUserInfo();
        $map['shop_id']=$userInfo['schoolId'];
        //$map['_org_id']=$userInfo['orgId'];
        //$ezDeviceList=Db::name('Ez_device')->alias('ed')->join('ez_device_config edc','ed.id=edc.ez_device_id')->where($map)->field('ed.acount_id,ed.acount_name,ed.validate_code,edc.channel_id,edc.channel_tag,edc.open_time')->select();
        $ezDeviceList=Db::name('Ez_device')->where($map)->select();
        $data=array();
        foreach($ezDeviceList as $key=>$value){
            $data[$key]=$this->getYsDeviceInfo($value['device_serial'],$value['id']);
            $data[$key]['list']=$this->getCameraList($value['device_serial'],$value['id']);
            $data[$key]['nick_name']=$value["_shop_name"];
        }
        return $data;
    }
    //获取设备的通道参数
    public function getChannelConfig($deviceSerial,$channelId){

    }



    //获取nvr对应的参数信息
    public function getNvrDeviceList(){
        $userInfo=getUserInfo();
        $map['shop_id']=$userInfo['schoolId'];
      //  $nvrDeviceList=Db::name('Nvr_device')->alias('nd')->join('nvr_device_config ndc','nd.id=ndc.nvr_device_id')->where($map)->field('nd.device_serial,nd.admin_username,channel_id,channel_tag,open_time')->select();
          $nvrDeviceList=Db::name('Nvr_device')->where($map)->select();
          $data=array();


          foreach($nvrDeviceList as $key=>$value){

            $deviceInfo=$this->getHttpDeviceList($value['admin_username'],$value['id']);
              $deviceInfo['list'][0]['device_type']='nvr';
            $data[]=$deviceInfo['list'][0];
          //  $data['device_type']='nvr';
          }

        return $data;
    }

    //通过admin_usernamer获取 nvr 平台设备列表
    public function getHttpDeviceList($account,$nvrDeviceId){
        $url='http://live.admin.haotuoguan.cn/openapi/device/list';
        //kjufq73a
        $data=array(
            'account'=>$account,
            'page_num'=>1,
            'page_size'=>100
        );
        $deviceArray=post_json_data($url,json_encode($data));
        foreach($deviceArray['list'][0]['list'] as $key=>$value){
            $configInfo=$this->getNvrConfig($nvrDeviceId,$value['chan_no']);
            if(empty($configInfo)){
                $openTime=array();
            }else{
                $configInfo['open_time']=str_replace('/','"',$configInfo['open_time']);
                $openTime= json_decode($configInfo['open_time'],true);
                if(!empty($configInfo['channel_tag'])) {

                    $deviceArray['list'][0]['list'][$key]['name'] = $configInfo['channel_tag'];
                }
            }
          $deviceArray['list'][0]['list'][$key]['openTime']=$openTime;
          //  $deviceArray['list'][0]['list'][$key]['videoInfo']=$this->getHtmlUrl($deviceArray['list'][0]['device_serial'],$deviceArray['list'][0]['list'][$key]['chan_no']);
        }
        return $deviceArray;
    }

    //测试获取html视频地址
    public function getHtmlUrl($deviceSerial,$channelId){
        $redis=getRedis();
        $url='http://live.admin.haotuoguan.cn/openapi/custom/v2/qiniu/html5';
        $data=array(
            'device_serial'=>$deviceSerial,
            'chan_no'=>$channelId,
            'option'=>1
        );
       if(empty($redis->get('nvr'.$deviceSerial.$channelId))) {
            $info = post_json_data($url, json_encode($data));
            $redis->set('nvr' . $deviceSerial . $channelId, $info, 120);
        }else{
           $info=$redis->get('nvr'.$deviceSerial.$channelId);
        }
        return $info;
    }

    //获取莹石的直播地址
    public function getEzVideoUrl($deviceSerial,$channelId){
        $redis=getRedis();
        $url="https://open.ys7.com/api/lapp/live/address/limited";
        $accessToken=$this->getEzAccessToken();
       $this->offEncryption($deviceSerial);
        if(empty($redis->get('ez'.$deviceSerial.$channelId))) {
            $data = array(
                'accessToken' => $accessToken,
                'deviceSerial' => $deviceSerial,
                'channelNo' => $channelId,
                'expireTime' => 1800
            );
            $jsonData = httpRequest($url, $data);
            $info = json_decode($jsonData, true);
            if ($info['code'] == 10002 || $info['code'] = 10001) {
                $accessTokenInfo = $this->getEzAccessToken(1);
                $data['accessToken'] = $accessTokenInfo['data']['accessToken'];
                $jsonData = httpRequest($url, $data);
                $info = json_decode($jsonData, true);
            }
            $redis->set('ez' . $deviceSerial . $channelId, $info, 1200);
        }else{
            $info=$redis->get('ez'.$deviceSerial.$channelId);
        }
        return $info;
}
    //关闭莹石视频加密
    public function offEncryption($deviceSerial){
        $url="https://open.ys7.com/api/lapp/device/encrypt/off";
        $map['device_serial']=$deviceSerial;
        $validate=Db::name('Ez_device')->where($map)->value('validate_code');
        $accessToken=$this->getEzAccessToken();
        $data=array(
            'accessToken'=>$accessToken,
            'deviceSerial'=>$deviceSerial,
            'validateCode'=>$validate
        );
        $result=httpRequest($url,$data);
        $info=json_decode($result,true);
        if($info['code']==10002||$info['code']=10001){
            $accessTokenInfo=$this->getEzAccessToken(1);
            $data['accessToken']=$accessTokenInfo['data']['accessToken'];
            $jsonData=httpRequest($url,$data);
            $info=json_decode($jsonData,true);
        }
        return $info;
    }

    //获取萤石的access_token,0:正常获取，1刷新获取
    public function getEzAccessToken($type=0){
        $redis=getRedis();
        $ezAccessTokenInfo=$redis->get('ezAccessTokenInfo');
        if(empty($ezAccessTokenInfo)||($ezAccessTokenInfo['data']['expireTime']<time()*1000||$type==1)) {
            $url = config('ez_url') . '/token/get';
            $appId = config('api_key');
            $secret = config('api_secret');
            $data = array(
                'appKey' => $appId,
                'appSecret' => $secret
            );

            $jsonData = httpRequest($url, $data);
            //{"data":{"accessToken":"at.447erbgg9uwtlohs3hr0yneud8uynre3-4g1xapfa94-1iyd2gx-8exjmgoil","expireTime":1528430539432},"code":"200","msg":"操作成功!"}
            $redis->set('ezAccessTokenInfo', json_decode($jsonData, true));
        }
        return $redis->get('ezAccessTokenInfo');
    }

    //获取莹石的设备信息
    public function getYsDeviceInfo($deviceSerial,$deviceNo){
        $url=config('ez_url').'/device/info';
        $accessTokenInfo=$this->getEzAccessToken();
        $data=array(
          'accessToken'=>$accessTokenInfo['data']['accessToken'],
          'deviceSerial'=>$deviceSerial
        );
        $jsonData=httpRequest($url,$data);
        $deviceInfo=json_decode($jsonData,true);
        if($deviceInfo['code']==100002){
            $accessTokenInfo=$this->getEzAccessToken(1);
            $data['accessToken']=$accessTokenInfo['data']['accessToken'];
            $jsonData=httpRequest($url,$data);
            $deviceInfo=json_decode($jsonData,true);
        }

        $info=array();
        $info['device_no']=$deviceNo;
        $info['device_serial']=$deviceSerial;
        $info['device_type']='ez';
        $info['device_type_name']=@$deviceInfo['data']['model'];
        $info['state']=@$deviceInfo['data']['status'];
        return $info;
    }

    //获取设备对应的摄像头列表(数量小于50时使用大于50还需要处理)
    public function getCameraList($deviceSerial,$deviceId){
        $url=config('ez_url').'/camera/list';
        $accessTokenInfo=$this->getEzAccessToken();
        $data=array(
            'accessToken'=>$accessTokenInfo['data']['accessToken'],
            'deviceSerial'=>$deviceSerial,
            'pageStart'=>0,
            'pageSize'=>50
        );
        $jsonData=httpRequest($url,$data);
        $cameraList=json_decode($jsonData,true);
        if($cameraList['code']==10002||$cameraList['code']=10001){
            $accessTokenInfo=$this->getEzAccessToken(1);
            $data['accessToken']=$accessTokenInfo['data']['accessToken'];
            $jsonData=httpRequest($url,$data);
            $cameraList=json_decode($jsonData,true);
        }
        $userCameraList=array();
        foreach($cameraList['data'] as $key=>$value){
            if($value['deviceSerial']==$deviceSerial){
                $currentInfo=array();
//                dump($value);
//                die;
                $configInfo=$this->getEzConfig($deviceId,$value['channelNo']);
                if(!empty($configInfo)) {
                    $currentInfo['name'] = $configInfo['channel_tag'];
                    $currentInfo['state']=$value['status'];
                    $currentInfo['chan_no']=$value['channelNo'];
                    $currentInfo['isEncrypt']=$value['isEncrypt'];
                    $configInfo['open_time']=str_replace('/','"',$configInfo['open_time']);
                    $currentInfo['openTime'] = json_decode($configInfo['open_time'],true);
                 //   $currentInfo['videoInfo']=$this->getEzVideoUrl($deviceSerial,$value['channelNo']);
                   // $currentInfo['openTime'] = $configInfo['open_time'];
                }
                $userCameraList[]= $currentInfo;
            }
        }
        return $userCameraList;
    }

    //通过具体的设备id和，channelId获取数据库的配置信息
    public function getEzConfig($ezDeviceId,$channelId){
        $map['ez_device_id']=$ezDeviceId;
        $map['channel_id']=$channelId;
        $map['effect']=1;
        $map['active']=1;
        $configInfo=Db::name('Ez_device_config')->where($map)->find();
        return $configInfo;
    }

    //通过具体的设备id和，channelId获取数据库的配置信息
    public function getNvrConfig($nvrDeviceId,$channelId){
        $map['nvr_device_id']=$nvrDeviceId;
        $map['channel_id']=$channelId;
        $map['effect']=1;
        $map['active']=1;
        $configInfo=Db::name('Nvr_device_config')->where($map)->find();
//        echo Db::getLastSql();
        return $configInfo;
    }

    //检查该设备的序列号和孩子的学校是否对应
    public function checkSchoolSerial($type,$deviceSerial){
        $userInfo=getUserInfo();
        $map['shop_id']=$userInfo['schoolId'];
       // $map['_org_id']=$userInfo['orgId'];
        $map['device_serial']=$deviceSerial;
        if($type=='ez'){
            $info=Db::name('Ez_device')->where($map)->find();
        }else if($type=='nvr'){
            $info=Db::name('Nvr_device')->where($map)->find();
        }
        if(empty($info)){
            renderInfo(400001,'该账户对应的学校,未引进该设备');
        }
    }







}
